package com.forgenet.testclient.net;


import com.forgenet.message.base.req.ReqCreateRolePacket;
import com.forgenet.message.base.req.ReqLoginRolePacket;
import com.forgenet.message.base.resp.RespCreateRolePacket;
import com.forgenet.message.base.resp.RespLoginRolePacket;
import com.forgenet.message.base.resp.RespGateLoginPacket;
import com.forgenet.testclient.ClientMain;
import com.forgenet.testclient.panel.*;
import com.sparrow.common.util.JsonUtil;
import com.sparrow.socket.tcp.codec.Request;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import javax.swing.*;

public class SimpleClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Request request = (Request) msg;
        int msgId = request.getMsgId();
        Object msgPacket = request.getMsg();
        if (msgPacket instanceof RespGateLoginPacket) {
            RespGateLoginPacket respGateLoginPacket = (RespGateLoginPacket) msgPacket;
            if (respGateLoginPacket.isCreateRole()) {
                String account = (String) ClientMain.cache.get("account");
                String roleName = (String) ClientMain.cache.get("roleName");
                ReqCreateRolePacket reqCreateRolePacket = new ReqCreateRolePacket();
                reqCreateRolePacket.setRoleName(roleName);
                reqCreateRolePacket.setAccount(account);
                ClientMain.channel.writeAndFlush(reqCreateRolePacket);
                System.out.println("请求创建角色");
            } else {
                ReqLoginRolePacket req = new ReqLoginRolePacket();
                ClientMain.channel.writeAndFlush(req);
                System.out.println("请求登录角色");
            }
        } else if (msgPacket instanceof RespCreateRolePacket) {
            ReqLoginRolePacket req = new ReqLoginRolePacket();
            ClientMain.channel.writeAndFlush(req);
            System.out.println("请求登录角色");
        } else if (msgPacket instanceof RespLoginRolePacket) {
            ClientMain.showPanel(TestMsgPanel.class);
        } else {
            TestMsgPanel.setText("收到消息:" + msgId
                    + "\n" + msgPacket.getClass().getSimpleName()+
                    "\n" + JsonUtil.toJSON(msgPacket));
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        SwingUtilities.invokeLater(() -> {
            JOptionPane.showMessageDialog(null, "与服务器的连接已断开！", "连接中断", JOptionPane.WARNING_MESSAGE);
            // 可选：回到 AuthPanel 或其他 UI
            ClientMain.showPanel(LoginGamePanel.class);
        });
        super.channelInactive(ctx);
    }
}

